//
//  LBMEmoticonToolBar.swift
//  EmoticonKeyboard
//
//  Created by 刘保满 on 16/5/30.
//  Copyright © 2016年 itheima. All rights reserved.
// 底部工具条

import UIKit

private let baseTag = 1001
class LBMEmoticonToolBar: UIStackView {

    
    //定义一个属性,用来记录选中的按钮
    var currentBtn: UIButton?
    //定义闭包
    var selectedIndexCallBack: ((index: Int) -> ())?
    
    init() {
        super.init(frame: CGRectZero)
        
//        backgroundColor = UIColor.redColor()
       //设置按钮在stackview中的排序为水平
        axis = .Horizontal
        //设置填充模式
        distribution = .FillEqually
        
        setupUI()
        
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI
    private func setupUI() {
        //由分组模型创建底部的按钮
        let packages = LBMEmoticonManager.sharedEmoticon.packages
        
        for i in 0..<packages.count {
            
            let package = packages[i]
            var backImageName = "compose_emotion_table_mid"
            if i == 0 {
                backImageName = "compose_emotion_table_left"
            } else if i == packages.count - 1 {
                backImageName = "compose_emotion_table_right"
            }
            
            addChildButtons(package.name!, backImageName: backImageName, index: i)
            
        }
        
    }
    
    
    //用来创建按钮的方法
    private func addChildButtons(title: String, backImageName: String, index: Int) {
        
        //实例化
        let btn = UIButton()
        btn.tag = index + baseTag
        btn.setTitle(title, forState: .Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Selected)
        btn.setBackgroundImage(UIImage(named: backImageName + "_normal"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: backImageName + "_selected"), forState: .Selected)

        btn.addTarget(self, action: #selector(LBMEmoticonToolBar.btnDidClick(_:)), forControlEvents: .TouchUpInside)

        addArrangedSubview(btn)
        //默认选中第0个
        if index == 0 {
            btn.selected = true
            currentBtn = btn
            
        }
        
        
    }
    //按钮点击事件
    @objc private func btnDidClick(btn: UIButton) {
        
        print("你点我干嘛")
        //点击按钮时,取消之前选中的
        currentBtn?.selected = false
        //当前点击的按钮为选中装填
        btn.selected = true
        //赋值
        currentBtn = btn
        //执行闭包回调
        selectedIndexCallBack?(index: btn.tag - baseTag)
        
    }
    
    ///定义一个方法,当表情视图滚动的时候,工具条上的按钮也联动
    func setSelectedBtn(section: Int) {
        
        let btntag = baseTag + section
        let btn = self.viewWithTag(btntag) as! UIButton
        currentBtn?.selected = false
        btn.selected = true
        currentBtn = btn

    }
    
    

}
